package com.taptech.doufu.ui.view.personalcenter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.personalcenter.PersonalInfoService;
import com.taptech.doufu.services.personalcenter.QQService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.ui.activity.PersonalInviteWeiboContactActivity;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.util.ArrayList;

public class PersonalInviteWindow extends PopupWindow implements
		HttpResponseListener {

	public static final int INVITE_TYPE_QQ = 1;
	public static final int INVITE_TYPE_QZONE = 2;
	public static final int INVITE_TYPE_WEIXIN = 3;
	public static final int INVITE_TYPE_FRIENDS = 4;
	String inviteCode,groupName;
	int groupId = -1;
	int type;
	private Activity activity;

	public PersonalInviteWindow(Activity activity, int groupId,String groupName) {
		super(activity);
		this.activity = activity;
		this.groupId = groupId;
		this.groupName = groupName;
		initView(activity);
	}

	private void initView(Activity activity) {
		View baseView = activity.getLayoutInflater().inflate(
				R.layout.personal_center_activity_invite, null);
		setFocusable(true);
		baseView.setFocusable(true);
		baseView.setFocusableInTouchMode(true);
		baseView.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK)
					dismiss();
				return true;
			}
		});
		setContentView(baseView);
		setWidth(LayoutParams.MATCH_PARENT);
		setHeight(LayoutParams.MATCH_PARENT);
		setBackgroundDrawable(new ColorDrawable());
		setAnimationStyle(R.style.Animation_Bottom_Top);
		setOutsideTouchable(true);
		showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0,
				0);

		baseView.findViewById(R.id.invite_phone).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
					}
				});

		baseView.findViewById(R.id.invite_qq_zone).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						shareToQZone(v);
					}
				});

		baseView.findViewById(R.id.invite_qq).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						inviteQQContact(v);
					}
				});

		baseView.findViewById(R.id.invite_weibo).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						inviteWeiboContact(v);
					}
				});

		baseView.findViewById(R.id.invite_weixin).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						inviteWeixinContact(v);
					}
				});

		baseView.findViewById(R.id.invite_weixin_friends).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						shareToFriends(v);
					}
				});

		baseView.findViewById(R.id.invite_cancel_btn).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						dismiss();
					}
				});
	}

	@Override
	public void handleResponse(int handleType, HttpResponseObject response) {
		try {
			switch (handleType) {
			case PersonalInfoService.HANDLE_GET_INVITE_CODE:
				if (response.getStatus() == 0) {
					JSONObject json = (JSONObject) response.getData();
					inviteCode = json.getString(Constant.INVITATION_CODE);
					sendMessage(type);
				} else {
					UIUtil.toastMessage(activity, DiaobaoUtil.getErrorTips(response));
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	public void inviteQQContact(View view) {
		invite(INVITE_TYPE_QQ);
	}

	public void

	inviteWeiboContact(View view) {
		this.dismiss();
//		mAccessToken.isSessionValid()
		if (WeiboService.mAccessToken == null || !WeiboService.mAccessToken.isSessionValid()) {
			WeiboService.getInstance().ssoAuthorize(activity,true,true);
			return;
		}
			 
		Intent intent = new Intent(activity,
				PersonalInviteWeiboContactActivity.class);
		intent.putExtra(Constant.GROUP_ID, groupId);
		intent.putExtra(Constant.GROUP_NAME, groupName);
		activity.startActivity(intent);
	}

	public void shareToFriends(View view) {
		invite(INVITE_TYPE_FRIENDS);
	}

	public void shareToQZone(View view) {
		invite(INVITE_TYPE_QZONE);
	}

	public void inviteWeixinContact(View view) {
		invite(INVITE_TYPE_WEIXIN);
	}

	private void invite(int type) {
		this.dismiss();
		this.type = type;
		PersonalInfoService.getInstance().getInviteCode(groupId, this,activity);

	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	private void sendMessage(int type) {
		if (type == INVITE_TYPE_QQ) {
			Bundle params = new Bundle();
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
			params.putString(QQShare.SHARE_TO_QQ_TITLE, "基友邀请");
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "豆花，女性向创作社区！邀请码【"+ inviteCode+"】");
			params.putString(QQShare.SHARE_TO_QQ_EXT_STR, "豆花，女性向创作社区！邀请码【"+ inviteCode+"】");
			params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, Constant.DOWN_URL_QQ);
			params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
					Constant.SHARE_IMAG_URL);
			params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "豆花");
			QQService.getInstance().shareToQQ(activity, params,
					new IUiListener() {

						@Override
						public void onError(UiError arg0) {
							TTLog.s(arg0.errorCode + ":::::"
									+ arg0.errorMessage);
						}

						@Override
						public void onComplete(Object arg0) {
						}

						@Override
						public void onCancel() {
						}
					});
		} else if (type == INVITE_TYPE_WEIXIN) {
			// 初始化一个WXTextObject对象
			WXTextObject textObj = new WXTextObject();
			textObj.text = PersonalInfoService.getInstance()
					.getWexinInviteMessage(inviteCode,groupName);

			// 用WXTextObject对象初始化一个WXMediaMessage对象
			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = textObj;
			// 发送文本类型的消息时，title字段不起作用
			// msg.title = "Will be ignored";
			msg.description = "豆花";

			// 构造一个Req
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
			req.message = msg;
			// req.scene = isTimelineCb.isChecked() ?
			// SendMessageToWX.Req.WXSceneTimeline :
			// SendMessageToWX.Req.WXSceneSession;

			// 调用api接口发送数据到微信

			IWXAPI wxAPI = WXAPIFactory.createWXAPI(activity,
					Constant.WX_APP_ID, true);
			wxAPI.registerApp(Constant.WX_APP_ID);

			wxAPI.sendReq(req);
		} else if (type == INVITE_TYPE_QZONE) {
			Bundle params = new Bundle();
			params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
					QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
			params.putString(QQShare.SHARE_TO_QQ_TITLE, "基友邀请");// 必填
			String inviteMessage = "豆花，女性向创作社区！邀请码【"+ inviteCode+"】";
			// params.putString(QQShare.SHARE_TO_QQ_EXT_STR,);
			params.putString(QQShare.SHARE_TO_QQ_SUMMARY, inviteMessage);// 选填
			params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, Constant.DOWN_URL_QQ);// 必填
			ArrayList<String> imgs = new ArrayList<String>();
			imgs.add(Constant.SHARE_IMAG_URL);

			params.putStringArrayList(QQShare.SHARE_TO_QQ_IMAGE_URL, imgs);
			QQService.getInstance().shareToQZone(activity, params,
					new IUiListener() {

						@Override
						public void onError(UiError arg0) {
							TTLog.s(arg0.errorCode + ":::::"
									+ arg0.errorMessage);
						}

						@Override
						public void onComplete(Object arg0) {
						}

						@Override
						public void onCancel() {
						}
					});
		} else if (type == INVITE_TYPE_FRIENDS) {
			// 初始化一个WXTextObject对象
			WXTextObject textObj = new WXTextObject();
			textObj.text = PersonalInfoService.getInstance()
					.getWexinInviteMessage(inviteCode,groupName);

			// 用WXTextObject对象初始化一个WXMediaMessage对象
			WXMediaMessage msg = new WXMediaMessage();
			msg.mediaObject = textObj;
			// 发送文本类型的消息时，title字段不起作用
			// msg.title = "Will be ignored";
			msg.description = "豆花";

			// 构造一个Req
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("text"); // transaction字段用于唯一标识一个请求
			req.message = msg;
			req.scene = SendMessageToWX.Req.WXSceneTimeline;

			// 调用api接口发送数据到微信

			IWXAPI wxAPI = WXAPIFactory.createWXAPI(activity,
					Constant.WX_APP_ID, true);
			wxAPI.registerApp(Constant.WX_APP_ID);

			wxAPI.sendReq(req);
		}
	}

}
